package org.tamal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.tamal.Session;

/**
 * This intercepter will prevent browsing any page without authentication.
 * @author Tamal Kanti Nath
 */
public final class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    private final Logger log = Logger.getLogger(getClass().getName());

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute(Session.USER.name()) != null) {
            return true;
        }
        if ("/spring/login".equals(request.getRequestURI())) {
            if (session.getAttribute(Session.FORWARD.name()) != null) {
                return true;
            }
            String referer = request.getHeader("Referer");
            if (referer == null) {
                session.setAttribute(Session.FORWARD.name(), "/");
            } else {
                session.setAttribute(Session.FORWARD.name(), referer);
            }
            return true;
        }
        log.debug("Request URI: " + request.getRequestURI());
        String forward = request.getRequestURI();
        if (request.getQueryString() != null) {
            forward += "?" + request.getQueryString();
        }
        session.setAttribute(Session.FORWARD.name(), forward);
        response.sendRedirect("/spring/login");
        return false;
    }
}
